package com.liuxu.waterrtc.service;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.liuxu.waterrtc.MLOC;
import com.liuxu.waterrtc.beauty.DemoVideoSourceCallback;
import com.liuxu.waterrtc.listener.XHLoginManagerListener;
import com.liuxu.waterrtc.listener.XHVoipManagerListener;
import com.liuxu.waterrtc.listener.XHVoipP2PManagerListener;
import com.liuxu.waterrtc.p2p.VoipP2PRingingActivity;
import com.liuxu.waterrtc.utils.AEvent;
import com.liuxu.waterrtc.utils.IEventListener;
import com.liuxu.waterrtc.voip.VoipAudioRingingActivity;
import com.liuxu.waterrtc.voip.VoipRingingActivity;
import com.starrtc.starrtcsdk.api.XHClient;
import com.starrtc.starrtcsdk.api.XHCustomConfig;
import com.starrtc.starrtcsdk.apiInterface.IXHErrorCallback;
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback;
import com.starrtc.starrtcsdk.core.camera.StarCamera;
import com.starrtc.starrtcsdk.core.videosrc.XHVideoSourceManager;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;



/**
 * Created by zhangjt on 2017/8/6.
 */

public class KeepLiveService extends Service implements IEventListener {
    private static  int SingalCount=0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MLOC.d("keeplive","我来了！");
        sendBroadCast("coming");
        startTimer();
        registerBroadcast();
    }

    private void startTimer() {

        Timer timer = new Timer();                    //创建一个定时器对象
        TimerTask task = new TimerTask()        //创建定时器任务对象，必须实现run方法，在该方法中定义用户任务
        {
            @Override
            public void run()
            {
                    if(SingalCount>3){
                        wakeUp();
                    }else {
                        sendBroadCast("hello");
                        if(MLOC.LiveEnable){
                        MLOC.d("keeplive","发出hello！");
                        SingalCount++;
                        }else{
                            MLOC.d("keeplive","守护已关闭！");
                    }
            }
            }
        };
        timer.schedule(task,0,3000);
    }
    private void sendBroadCast(String message){
        Intent intent = new Intent();
        intent.setAction("waterrtc");
        intent.putExtra("message",message);
        sendBroadcast(intent);
    }
    @Override
    public void onDestroy() {
        MLOC.d("keeplive","临终遗言！");
        sendBroadCast("killed");
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }
    void registerBroadcast(){
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("waterapp");
        registerReceiver(mReceiver, mFilter);
    }
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getStringExtra("message")){
                case "hello":{
                    MLOC.d("keeplive","收到hello！");
                    SingalCount=0;
                    break;
                }
                case "killed":{
                    MLOC.d("keeplive","站起来！");
                    wakeUp();
                    break;
                }
            }
        }
    };
    private void wakeUp(){
        if(MLOC.LiveEnable){
            PackageManager packageManager = this.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage("com.soarsun.WaterApp");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else {
            SingalCount=0;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initSDK();
        return super.onStartCommand(intent, flags, startId);
    }

    private void initSDK(){
        MLOC.init(this);
        initFree();
    }

    private boolean isLogin = false;
    //开放版SDK初始化
    private void initFree(){
        MLOC.d("KeepLiveService","initFree");
        isLogin = XHClient.getInstance().getIsOnline();
        if(!isLogin){
            if(MLOC.userId.equals("")){
                MLOC.userId = ""+(new Random().nextInt(900000)+100000);
                MLOC.saveUserId(MLOC.userId);
            }
            addListener();

            XHCustomConfig customConfig =  XHCustomConfig.getInstance(this);
            customConfig.setChatroomServerUrl(MLOC.CHATROOM_SERVER_URL);
            customConfig.setLiveSrcServerUrl(MLOC.LIVE_SRC_SERVER_URL);
            customConfig.setLiveVdnServerUrl(MLOC.LIVE_VDN_SERVER_URL);
            customConfig.setImServerUrl(MLOC.IM_SERVER_URL);
            customConfig.setVoipServerUrl(MLOC.VOIP_SERVER_URL);
//            customConfig.setLogEnable(false); //关闭SDK调试日志
//            customConfig.setDefConfigOpenGLESEnable(false);
//            customConfig.setDefConfigCameraId(1);//设置默认摄像头方向  0后置  1前置
//            customConfig.setDefConfigVideoSize(XHConstants.XHCropTypeEnum.STAR_VIDEO_CONFIG_360BW_640BH_180SW_320SH);
//            customConfig.setLogDirPath(Environment.getExternalStorageDirectory().getPath()+"/starrtcLog");
            customConfig.setDefConfigCamera2Enable(false);
            StarCamera.setFrameBufferEnable(false);
            customConfig.initSDKForFree(MLOC.userId, new IXHErrorCallback() {
                @Override
                public void error(final String errMsg, Object data) {
                    MLOC.e("KeepLiveService","error:"+errMsg);
                    MLOC.showMsg(KeepLiveService.this,errMsg);
                }
            },new Handler());

            XHClient.getInstance().getVoipManager().addListener(new XHVoipManagerListener());
            XHClient.getInstance().getVoipP2PManager().addListener(new XHVoipP2PManagerListener());
            XHClient.getInstance().getLoginManager().addListener(new XHLoginManagerListener());
            XHVideoSourceManager.getInstance().setVideoSourceCallback(new DemoVideoSourceCallback());

            XHClient.getInstance().getLoginManager().loginFree(new IXHResultCallback() {
                @Override
                public void success(Object data) {
                    MLOC.d("KeepLiveService","loginSuccess");
                    isLogin = true;
                }
                @Override
                public void failed(final String errMsg) {
                    MLOC.d("KeepLiveService","loginFailed "+errMsg);
                    MLOC.showMsg(KeepLiveService.this,errMsg);
                }
            });
        }
    }

    @Override
    public void dispatchEvent(String aEventID, boolean success, Object eventObj) {
        switch (aEventID){
            case AEvent.AEVENT_VOIP_REV_CALLING:{
                Intent intent = new Intent(this, VoipRingingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                intent.putExtra("targetId",eventObj.toString());
                startActivity(intent);
            }
//                if(MLOC.canPickupVoip){
//                    Intent intent = new Intent(this, VoipRingingActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
//                    intent.putExtra("targetId",eventObj.toString());
//                    startActivity(intent);
//                }else{
//                    MLOC.hasNewVoipMsg = true;
//                }
                break;
            case AEvent.AEVENT_VOIP_REV_CALLING_AUDIO:
                if(MLOC.canPickupVoip){
                    Intent intent = new Intent(this, VoipAudioRingingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                    intent.putExtra("targetId",eventObj.toString());
                    startActivity(intent);
                }else{
                    MLOC.hasNewVoipMsg = true;
                }
                break;
            case AEvent.AEVENT_VOIP_P2P_REV_CALLING:
                if(MLOC.canPickupVoip){
                    Intent intent = new Intent(this, VoipP2PRingingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                    intent.putExtra("targetId",eventObj.toString());
                    startActivity(intent);
                }
                break;
            case AEvent.AEVENT_VOIP_P2P_REV_CALLING_AUDIO:
                if(MLOC.canPickupVoip){
                    Intent intent = new Intent(this, VoipP2PRingingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                    intent.putExtra("targetId",eventObj.toString());
                    startActivity(intent);
                }
                break;
            case AEvent.AEVENT_C2C_REV_MSG:
            case AEvent.AEVENT_REV_SYSTEM_MSG:
                MLOC.hasNewC2CMsg = true;
                break;
            case AEvent.AEVENT_GROUP_REV_MSG:
                MLOC.hasNewGroupMsg = true;
                break;
            case AEvent.AEVENT_LOGOUT:
                removeListener();
                this.stopSelf();
                break;
        }
    }

    private void addListener(){
        AEvent.addListener(AEvent.AEVENT_LOGOUT,this);
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_CALLING,this);
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_CALLING_AUDIO,this);
        AEvent.addListener(AEvent.AEVENT_VOIP_P2P_REV_CALLING,this);
        AEvent.addListener(AEvent.AEVENT_C2C_REV_MSG,this);
        AEvent.addListener(AEvent.AEVENT_REV_SYSTEM_MSG,this);
        AEvent.addListener(AEvent.AEVENT_GROUP_REV_MSG,this);
    }

    private void removeListener(){
        AEvent.removeListener(AEvent.AEVENT_LOGOUT,this);
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_CALLING,this);
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_CALLING_AUDIO,this);
        AEvent.removeListener(AEvent.AEVENT_VOIP_P2P_REV_CALLING,this);
        AEvent.removeListener(AEvent.AEVENT_C2C_REV_MSG,this);
        AEvent.removeListener(AEvent.AEVENT_REV_SYSTEM_MSG,this);
        AEvent.removeListener(AEvent.AEVENT_GROUP_REV_MSG,this);
    }

}
